package gameuserlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/common/utils"
	"navi-mumbai/third/game/wz"
	"strconv"

	//"navi-mumbai/app/rpc/model/pg/game"

	"navi-mumbai/app/rpc/game/internal/svc"
	"navi-mumbai/app/rpc/game/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginGameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginGameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginGameLogic {
	return &LoginGameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登陆G端
func (l *LoginGameLogic) LoginGame(in *pb.LoginGameReq) (*pb.LoginGameResp, error) {
	defer utils.RecoverPanic()

	// 查询open id
	var err error
	//
	var rsp *pb.GetOpenIdByUidResp
	rsp, err = NewGetOpenIdByUidLogic(l.ctx, l.svcCtx).GetOpenIdByUid(&pb.GetOpenIdByUidReq{
		Uid:        in.Uid,
		ProviderId: in.ProviderId,
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	// gen token
	var rsp2 *pb.GenGameTokenResp
	rsp2, err = NewGenGameTokenLogic(l.ctx, l.svcCtx).GenGameToken(&pb.GenGameTokenReq{
		OpenId:     rsp.OpenId,
		ProviderId: in.ProviderId,
		Nickname:   rsp.Nickname,
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	var resp pb.LoginGameResp
	resp.OpenId = rsp.OpenId
	resp.Nickname = rsp.Nickname

	// 请求G端接口
	wzReq := wz.AuthReq{
		Uid:   strconv.FormatInt(rsp.OpenId, 10),
		User:  rsp.Nickname,
		Token: rsp2.Token,
	}
	l.Logger.Infof("LoginGame Uid: %s User: %s Token: %s ", wzReq.Uid, wzReq.User, wzReq.Token)

	var wzResp *wz.AuthResp
	wzResp, err = wz.Hc.Auth(&wzReq)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	resp.GToken = wzResp.Data
	return &resp, nil
}
